const http = require("http");
const fs = require("fs");

http
  .createServer((req, res) => {
    const url = req.url;
    if (url === "/" || url === "/index-fetch.html") {
      fs.readFile("index-fetch.html", (err, data) => {
        if (err) {
          res.writeHead(500);
          res.end("Error loading");
        } else {
          res.writeHead(200, { "Content-Type": "text/html" });
          res.end(data);
        }
      });
    } else if (url.includes("/fetch-sse")) {
        console.log('sse request')
      let body = "";
      req.on("data", (chunk) => {
        body += chunk;
      });

      res.writeHead(200, {
        "Content-Type": "application/json",
        "Cache-Control": "no-cache",
        Connection: "keep-alive",
        "Access-Control-Allow-Origin": "*",
        "access-control-allow-methods": 'POST',
        'access-control-allow-headers': 'Content-Type'
      });

      let id = 0;
      console.log('id: ', id)
      const intervalId = setInterval(() => {
        const data = JSON.stringify({
          id,
          time: new Date().toISOString(),
          body: JSON.parse(body),
        });
        res.write(`${data}\n`);
        id++;
        console.log('id: ', id)
        if (id >= 10) {
          clearInterval(intervalId);
          res.end();
        }
      }, 1000);

      req.on("close", () => {
        clearInterval(intervalId);
        res.end();
      });
    } else {
      res.writeHead(404);
      res.end();
    }
  })
  .listen(3001);

console.log("Fetch SSE Server running at http://localhost:3001/");
